package com.hcinfos.gsoo.ui;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.Dining;
import com.amap.api.services.poisearch.Photo;
import com.amap.api.services.poisearch.PoiItemDetail;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.amap.api.services.poisearch.PoiSearch.SearchBound;
import com.baidu.location.LocationClient;
import com.hcinfos.gsoo.GsooApplication;
import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.adapter.ShopListAdapter;
import com.hcinfos.gsoo.adapter.TypeDoubleSelectAdapter;
import com.hcinfos.gsoo.adapter.TypeSingleSelectAdapter;
import com.hcinfos.gsoo.config.Common;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.enity.City;
import com.hcinfos.gsoo.enity.Type;
import com.hcinfos.gsoo.enity.UrlImage;
import com.hcinfos.gsoo.enity.ViewSuppSearchExt;
import com.hcinfos.gsoo.https.HttpClientUtil;
import com.hcinfos.gsoo.json.LBSInfoJson;
import com.hcinfos.gsoo.service.LocationService;
import com.hcinfos.gsoo.util.DateUtil;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;
import com.hcinfos.gsoo.view.DropDownListView;
import com.hcinfos.gsoo.view.DropDownListView.OnDropDownListener;

public class ListDisplayActivity extends Activity implements OnClickListener,
		OnPoiSearchListener {

	private TextView ds_select, type_select, sort_select;
	private ListView single_listView, typeListView, subTypeListView;
	private TypeSingleSelectAdapter singleAdapter;
	private TypeDoubleSelectAdapter typeAdapter, subTypeAdapter;
	private List<String> distanceList, sortList;
	private RelativeLayout tc_select_category_layout;
	private DropDownListView shopListView;
	private ShopListAdapter shopAdapter;
	private List<ViewSuppSearchExt> shopList;
	private Map<String, Double> distanceMap = new HashMap<String, Double>();

	private TextView reg_tv;
	private ImageButton left_ib;
	private TextView center_tv;
	private ImageView right_img;

	private LinearLayout loading_dialog_content_layout;
	private RelativeLayout loading_staus_rl;
	private TextView status_tv;
	private RelativeLayout progress_layout;

	private View moreView;
	private ProgressBar pageBar;
	private TextView loading_tv;
	private RelativeLayout load_rl;

	private Button add_button;
	private RelativeLayout tv_select1_rl;

	private SharePreferenceUtil util;

	private Type currentType;
	private int typePosition = 0;
	private List<Type> subList;
	private int distancePosition = 4;
	private int sortPosition = 0;
	private String lat = "23.056571";
	private String lng = "113.714749";
	private int rows = 10;
	private int page = 0;
	private int csOrder = 0;
	private double distance = 2d;// 公里
	private String typeId = "040b27f2e5084d7f9891898195043d80,382ae00ab4a14c90a6b9867ff5d1f863,9457105c3a6f49b78def4f1553d16858,c2a97ada018841e6a1cb71fb6efb3f63,36f76d8c3f634f6d905dfd195a815592,8bd36522dd1f4dd4a5a692b64e0b4846,1a2fce881cf64ab99815dcfa056a643e,9274ce9580764ffeb8dab7a9956fc21d,f29faee34ee84cf0adc4552d5b7474eb,083cfaf24c294251a9822700a7a9abfe,229ba7646ed94f05b5c3bc78f89090a5,1b79cb6389274fcab43aade063426436,202afa581577467ba987f5ab3686564f,4e1abe5fe6d543f3b6b6f6c33e375311,a2eef889b32e457a9d1eb7e0684c2407,aac72832fa5d4666b172ffe6dc33e3fd,04dd61f6d72b46bc834262de6e0e6506,fdda9e479c3246809200e0fc20e74e8f,4908b224188d4c23b77bfd9f9e26b162,73fa4401fdcb48e2928053ee468bea4c,d10c831a71a44137be693da9a32e6cdc,db34df71978a4041b7443af756fe6f20,efb61a225a144fa5887ef85ad1e6b3fb,52359ac526744458961a94ee67548623,2a4a5eb53ece47239015ff1d702b30f2,dbd26ecac42f40b2a78c5d0f9a1cce1b,1e7221aba3e34b16a9cb0db3eecdaea2,2409ad531a344811a2ea2cec0c448011,ffe51c07201a4505b33724da23bf989c,fdcd6fcac89541f19af4618e9c4dc78a,c9d34dc6edee4d1ca7f4cfa63842c6d0,ad472e924041410a96897761c252798f,8ccc2044f35548ab85e1746d2d59ff27,7fe93852962b414798a98416c82f2833";
	private int totalNums = 0;
	private int currentId = -1;
	private int currentPage = 0;
	private Intent intent;

	private String typeName = "美食";
	private List<Type> list;

	private final int GET_TYPE_FAIL = 0x2220;
	private final int GET_TYPE_SUCCESS = GET_TYPE_FAIL + 1;
	private final int OBTAIN_SHOP_SUCCESS = GET_TYPE_FAIL + 2;
	private final int OBTAIN_SHOP_END = GET_TYPE_FAIL + 3;
	private final int OBTAIN_POI_START = GET_TYPE_FAIL + 4;
	private final int OBTAIN_SHOP_FAIL = GET_TYPE_FAIL + 5;
	private final int OBTAIN_POI_SUCCESS = GET_TYPE_FAIL + 6;
	private final int OBTAIN_POI_FAIL = GET_TYPE_FAIL + 8;
	private final int OBTAIN_POI_REFRESH = GET_TYPE_FAIL + 9;
	private final int OBTAIN_POI_END = GET_TYPE_FAIL + 10;

	private Context context;
	private List<ViewSuppSearchExt> resultList = null;
	private String areaId = null;
	private boolean isLastPage = false;// 判断是否是最后一页
	private boolean isDropDown = true;

	private boolean isRequestLocation = false;

	private PoiSearch.Query query;
	private PoiSearch poiSearch;
	private int distanceQuery = 8000;
	private List<ViewSuppSearchExt> poiList;
	private String cityName = null;

	private List<PoiItem> poiItems;
	private Map<String, Integer> saveDistance = new HashMap<String, Integer>();
	private PoiResult poiResult = null;
	private boolean isLoadPOI = false;
	private LocationClient locationClient;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_listdisplay);
		locationClient = ((GsooApplication) getApplication()).mLocationClient;

		IntentFilter filter = new IntentFilter(LocationService.LOCATION_ACTION);
		registerReceiver(locationReceiver, filter);

		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		util = new SharePreferenceUtil(this, "setting");
		String foodType = util.loadStringSharedPreference("foodType");
		if (foodType != null) {
			typeId = foodType;
		}
		list = new ArrayList<Type>();
		context = this;
		initRes();
		obtainType();
		initData();

	}

	private boolean isSameCity = true;

	private void obtainData() {

		City city = (City) util.loadObject("city");
		try {
			if (city != null) {
				if (GsooApplication.lat == null) {
					locationClient.start();
				} else {
					lat = GsooApplication.lat + "";
					lng = GsooApplication.lng + "";
					if (GsooApplication.cityName != null
							&& GsooApplication.cityName.equals(city.getName())) {
						isSameCity = true;
						distance = 200;
					} else {
						distance = 6000;
						isSameCity = false;
					}
					areaId = city.getCityId();
					cityName = city.getName();
					obtainShopInfo();
				}
			} else {

				// 未开通提示
			}
		} catch (Exception e) {
			LogUtil.d("wxf", "otainData " + e.toString());
		}

	}

	BroadcastReceiver locationReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {

			LogUtil.d("wxf", "HomeActivity  location Receiver........");
			obtainData();
		}

	};

	private void initRes() {
		tv_select1_rl = (RelativeLayout) findViewById(R.id.tv_select1_rl);

		add_button = (Button) findViewById(R.id.add_button);
		add_button.setOnClickListener(this);

		left_ib = (ImageButton) findViewById(R.id.left_ib);
		left_ib.setOnClickListener(this);
		left_ib.setVisibility(View.GONE);
		reg_tv = (TextView) findViewById(R.id.reg_tv);
		reg_tv.setVisibility(View.GONE);
		center_tv = (TextView) findViewById(R.id.center_tv);
		center_tv.setText("美食");
		right_img = (ImageView) findViewById(R.id.right_img);
		right_img.setBackgroundResource(R.drawable.wb_title_change_map_btn);
		right_img.setVisibility(View.GONE);
		right_img.setOnClickListener(this);

		tc_select_category_layout = (RelativeLayout) findViewById(R.id.tc_select_category_layout);
		ds_select = (TextView) findViewById(R.id.tc_select1);
		ds_select.setOnClickListener(this);
		type_select = (TextView) findViewById(R.id.tc_select2);
		type_select.setOnClickListener(this);
		sort_select = (TextView) findViewById(R.id.tc_select3);
		sort_select.setOnClickListener(this);

		single_listView = (ListView) findViewById(R.id.tc_select_single_listview);
		singleAdapter = new TypeSingleSelectAdapter(this,
				new ArrayList<String>());
		single_listView.setAdapter(singleAdapter);
		single_listView.setOnItemClickListener(singleListItemOnclickListener);

		typeListView = (ListView) findViewById(R.id.tc_select_listview);
		typeAdapter = new TypeDoubleSelectAdapter(this, new ArrayList<Type>());
		typeListView.setAdapter(typeAdapter);
		typeListView.setOnItemClickListener(typeListItemOnclickListener);
		subTypeListView = (ListView) findViewById(R.id.tc_select_subListView);
		subTypeAdapter = new TypeDoubleSelectAdapter(this,
				new ArrayList<Type>());
		subTypeListView.setAdapter(subTypeAdapter);
		subTypeListView.setOnItemClickListener(subTypeListItemOnclickListener);

		shopListView = (DropDownListView) findViewById(R.id.shopList);
		shopListView.setHeadViewVisible(View.GONE);
		shopListView.setOnItemClickListener(listItemClickListener);
		shopListView.setOnDropDownListener(dropDownListener);
		shopListView.setOnBottomListener(new OnClickListener() {

			public void onClick(View v) {
				isDropDown = false;
				obtainShopInfo();
			}
		});
		shopListView.setVisibility(View.GONE);
		shopList = new ArrayList<ViewSuppSearchExt>();
		shopAdapter = new ShopListAdapter(this, shopList);
		shopListView.setAdapter(shopAdapter);

		tc_select_category_layout.setOnTouchListener(typeSelectTouchListener);
		progress_layout = (RelativeLayout) findViewById(R.id.progress_layout);
		progress_layout.setOnClickListener(this);
		progress_layout.setVisibility(View.VISIBLE);
		loading_dialog_content_layout = (LinearLayout) findViewById(R.id.loading_dialog_content_layout);
		loading_staus_rl = (RelativeLayout) findViewById(R.id.loading_staus_rl);
		loading_staus_rl.setVisibility(View.GONE);// 内容提示
		loading_dialog_content_layout.setVisibility(View.VISIBLE);// 加载条
		status_tv = (TextView) findViewById(R.id.status_tv);
		status_tv.setVisibility(View.GONE);
		currentType = (Type) getIntent().getSerializableExtra("type");
		if (currentType != null) {
			typeId = currentType.getId();
			LogUtil.d("wxf", "typeId:" + typeId);
			center_tv.setText(currentType.getTypeName());
		}
	}

	OnTouchListener typeSelectTouchListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			tc_select_category_layout.setVisibility(View.GONE);
			setUnSelectStyle(ds_select);
			setUnSelectStyle(sort_select);
			setUnSelectStyle(type_select);
			currentId = -1;
			return true;
		}
	};

	protected void onResume() {
		obtainData();
		super.onResume();
		LogUtil.d("wxf", "ListDisplay onResume");
	};

	private void initData() {
		distanceList = new ArrayList<String>();
		distanceList.add("0.5公里");
		distanceList.add("2.5公里");
		distanceList.add("4.5公里");
		distanceList.add("20.0公里");
		distanceList.add("全城");
		distanceMap.put("0", 1.0);
		distanceMap.put("1", 2.5);
		distanceMap.put("2", 4.5);
		distanceMap.put("3", 20.0);
		distanceMap.put("4", 200.0);

		sortList = new ArrayList<String>();
		sortList.add("人气指数");
		sortList.add("人均消费低-高");
		sortList.add("人均消费高-低");
		sortList.add("评分指数");

	}

	OnItemClickListener singleListItemOnclickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View view, int position,
				long arg3) {

			switch (currentId) {
			case R.id.tc_select1:
				distancePosition = position;
				ds_select.setText(distanceList.get(position));
				singleAdapter.setPosition(distancePosition);
				distance = distanceMap.get(position + "");
				LogUtil.d("wxf", "distance:" + distance);
				break;
			case R.id.tc_select3:
				sort_select.setText(sortList.get(position));
				sortPosition = position;
				singleAdapter.setPosition(sortPosition);
				csOrder = position;
				break;
			}
			currentId = -1;
			add_button.setVisibility(View.GONE);
			tc_select_category_layout.setVisibility(View.GONE);
			setUnSelectStyle(type_select);
			setUnSelectStyle(ds_select);
			setUnSelectStyle(sort_select);
			page = 0;
			currentPage = 0;
			shopList.clear();
			isLastPage = false;
			isDropDown = true;
			shopListView.setHasMore(true);
			obtainShopInfo();
			progress_layout.setVisibility(View.VISIBLE);
			shopListView.setVisibility(View.GONE);
			loading_staus_rl.setVisibility(View.GONE);// 内容提示
			loading_dialog_content_layout.setVisibility(View.VISIBLE);// 加载条
		}
	};

	OnItemClickListener typeListItemOnclickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View view, int position,
				long arg3) {
			currentId = -1;
			typePosition = position;
			typeAdapter.setPosition(position);
			subList = list.get(position).getSubTypeList();
			subTypeAdapter.setDataChange(subList);
		}
	};
	OnItemClickListener subTypeListItemOnclickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View view, int position,
				long arg3) {

			currentId = -1;
			add_button.setVisibility(View.GONE);
			tc_select_category_layout.setVisibility(View.GONE);
			setUnSelectStyle(type_select);
			setUnSelectStyle(ds_select);
			setUnSelectStyle(sort_select);
			if (subList == null)
				return;
			Type type = subList.get(position);
			center_tv.setText(type.getTypeName());
			type_select.setText(type.getTypeName());
			typeId = type.getId();
			typeName = type.getTypeName();
			page = 0;
			currentPage = 0;
			shopList.clear();
			// poiSearch = null;
			isLastPage = false;
			isDropDown = true;
			shopListView.setHasMore(true);
			obtainShopInfo();
			progress_layout.setVisibility(View.VISIBLE);
			shopListView.setVisibility(View.GONE);
			loading_staus_rl.setVisibility(View.GONE);// 内容提示
			loading_dialog_content_layout.setVisibility(View.VISIBLE);// 加载条
		}
	};

	private void setUnSelectStyle(TextView view) {

		view.setTextColor(getResources().getColor(R.color.B_black_50));
		Drawable drawable = getResources().getDrawable(R.drawable.arrow_down);
		drawable.setBounds(0, 0, drawable.getMinimumWidth(),
				drawable.getMinimumHeight());
		view.setCompoundDrawables(null, null, drawable, null);
	}

	OnItemClickListener listItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {

			intent = new Intent(ListDisplayActivity.this,
					ShopDetailActivity.class);
			ViewSuppSearchExt detail = shopList.get(position);
			intent.putExtra("shopDetail", detail);
			startActivity(intent);
		}
	};

	OnDropDownListener dropDownListener = new OnDropDownListener() {

		@Override
		public void onDropDown() {
			isDropDown = true;
			obtainShopInfo();
		}

	};

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		if (locationReceiver != null)
			unregisterReceiver(locationReceiver);
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.tc_select1:

			if (currentId == v.getId()) {
				tc_select_category_layout.setVisibility(View.GONE);
				setUnSelectStyle(ds_select);
				currentId = -1;
				return;
			}
			tc_select_category_layout.setVisibility(View.VISIBLE);
			single_listView.setVisibility(View.VISIBLE);
			singleAdapter.setPosition(distancePosition);
			singleAdapter.setDataChange(distanceList);
			setSelectStyle(ds_select);
			setUnSelectStyle(type_select);
			setUnSelectStyle(sort_select);
			typeListView.setVisibility(View.GONE);
			currentId = v.getId();
			break;
		case R.id.tc_select2:
			if (currentId == v.getId()) {
				tc_select_category_layout.setVisibility(View.GONE);
				setUnSelectStyle(type_select);
				currentId = -1;
				return;
			}
			single_listView.setVisibility(View.GONE);
			tc_select_category_layout.setVisibility(View.VISIBLE);
			typeListView.setVisibility(View.VISIBLE);
			typeAdapter.setPosition(typePosition);
			// add_button.setVisibility(View.GONE);
			// typeAdapter.setDataChange(typeList);
			// subTypeAdapter.setDataChange(subTypeList);
			subTypeAdapter.setSub(true);
			setSelectStyle(type_select);
			setUnSelectStyle(ds_select);
			setUnSelectStyle(sort_select);
			currentId = v.getId();
			break;
		case R.id.tc_select3:
			if (currentId == v.getId()) {
				tc_select_category_layout.setVisibility(View.GONE);
				currentId = -1;
				setUnSelectStyle(sort_select);
				return;
			}
			// add_button.setVisibility(View.GONE);
			tc_select_category_layout.setVisibility(View.VISIBLE);
			single_listView.setVisibility(View.VISIBLE);
			singleAdapter.setPosition(sortPosition);
			singleAdapter.setDataChange(sortList);
			setSelectStyle(sort_select);
			setUnSelectStyle(ds_select);
			setUnSelectStyle(type_select);
			typeListView.setVisibility(View.GONE);
			currentId = v.getId();
			break;
		case R.id.right_img:

			break;
		case R.id.left_ib:
			finish();
			break;
		}
	}

	private void setSelectStyle(TextView view) {
		view.setTextColor(Color.parseColor("#00adef"));
		Drawable drawable = getResources().getDrawable(
				R.drawable.arrow_up_hilight);
		drawable.setBounds(0, 0, drawable.getMinimumWidth(),
				drawable.getMinimumHeight());
		view.setCompoundDrawables(null, null, drawable, null);
	}

	/**
	 * 获得类别
	 */
	private void obtainType() {

		new Thread(new Runnable() {
			@Override
			public void run() {
				try {

					String cacheRes = util.loadStringSharedPreference("type");

					if (null != cacheRes && cacheRes.trim().length() > 0) {
						parserJsonData(cacheRes);
						LogUtil.d("wxf", "type=" + cacheRes);
					} else {
						String result = HttpClientUtil.getFromWebByHttpClient(
								ListDisplayActivity.this, Urls.GET_ALL_TYPE);
						if (result == null) {
							Message msg = handler.obtainMessage();
							msg.what = GET_TYPE_FAIL;
							handler.sendMessage(msg);
						} else {
							util.removeKey("type");
							util.saveSharedPreferences("type", result);
							GsooApplication.cacaheMap.put(Urls.GET_ALL_TYPE,
									result);
							parserJsonData(result);
						}
						LogUtil.d("wxf", "type:" + result);
					}

				} catch (Exception e) {
					Message msg = handler.obtainMessage();
					msg.what = GET_TYPE_FAIL;
					handler.sendMessage(msg);
					LogUtil.e("wxf", "type:" + e.toString());
				}
			}
		}).start();
	}

	/**
	 * 数据json解析
	 * 
	 * @throws Exception
	 */
	StringBuffer sb = new StringBuffer();

	private void parserJsonData(String result) throws Exception {

		JSONObject obj = new JSONObject(result);
		int state = obj.getInt("state");
		String message = obj.getString("message");
		if (state == 200) {
			JSONArray array = obj.getJSONArray("rows");
			for (int i = 0; i < array.length(); i++) {
				Type type = new Type();
				JSONObject typeObj = array.getJSONObject(i);
				if (!typeObj.isNull("areaId")) {
					type.setAreaId(typeObj.getString("areaId"));
				}
				type.setId(typeObj.getString("id"));
				type.setTypeName(typeObj.getString("typeName"));
				List<Type> subList = new ArrayList<Type>();

				boolean isFood = false;
				if (type.getTypeName().equals("美食")) {
					isFood = true;
				} else {
					isFood = false;
				}
				if (!typeObj.isNull("subTypeArray")) {
					JSONArray subArray = typeObj.getJSONArray("subTypeArray");
					for (int j = 0; j < subArray.length(); j++) {
						JSONObject subObj = subArray.getJSONObject(j);
						Type subType = new Type();
						subType.setId(subObj.getString("id"));
						subType.setTypeName(subObj.getString("typeName"));
						subList.add(subType);
						if (isFood) {
							if (subArray.length() > 0
									&& j == subArray.length() - 1) {
								sb.append(subType.getId());
							} else {
								sb.append(subType.getId() + ",");
							}
						}
					}
				}
				type.setSubTypeList(subList);
				list.add(type);
			}
			util.saveSharedPreferences("foodType", sb.toString());
			Message msg = handler.obtainMessage();
			msg.what = GET_TYPE_SUCCESS;
			handler.sendMessage(msg);

		} else {
			Message msg = handler.obtainMessage();
			msg.what = GET_TYPE_FAIL;
			msg.obj = message;
			handler.sendMessage(msg);
		}
	}

	/**
	 * 网络数据请求
	 */
	private void obtainShopInfo() {

		if (!isLoadPOI) {
			if (isLastPage) {
				shopListView.onDropDownComplete("上次刷新时间:"
						+ DateUtil.getCurrentTime());
				shopListView.onBottomComplete();
				return;
			}
			if (!isDropDown) {
				page += 1;
			} else {
				page = 1;
			}
		}
		new Thread(new Runnable() {

			@Override
			public void run() {

				String url = Urls.SHOP_LIST + "lsbaiAreaId=" + areaId
						+ "&csrecord.lon=" + lng + "&csrecord.lat=" + lat
						+ "&csrecord.kmScope=" + distance + "&csrecord.typeId="
						+ typeId + "&csOrder=" + csOrder + "&page=" + page
						+ "&rows=" + rows;
				LogUtil.d("wxf", "obtainShopInfo url:" + url);
				try {
					String result = HttpClientUtil.getFromWebByHttpClient(
							context, url);
					LogUtil.d("wxf", "lbs:result:" + result);
					resultList = LBSInfoJson.getLbsInfoListByJson(result);
					int state = LBSInfoJson.state;
					totalNums = LBSInfoJson.totalNums;
					if (state == 200 && totalNums > 0) {
						if (resultList != null) {
							for (ViewSuppSearchExt ext : resultList) {
								ext.setDistance(ext.getDistance() * 1000);
							}
						}
						if (resultList.size() < rows) {
							handler.sendEmptyMessage(OBTAIN_SHOP_END);
							return;
						}
						handler.sendEmptyMessage(OBTAIN_SHOP_SUCCESS);
					} else {
						handler.sendEmptyMessage(OBTAIN_POI_START);
					}

				} catch (Exception e) {
					handler.sendEmptyMessage(OBTAIN_SHOP_FAIL);
					LogUtil.e("wxf", "obtainShopInfo=" + e.toString());
				}
			}
		}).start();
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {

			case GET_TYPE_SUCCESS:
				if (list.size() > 0) {
					typeAdapter.setDataChange(list);
					subList = list.get(0).getSubTypeList();
					subTypeAdapter.setDataChange(subList);
				}
				break;
			case GET_TYPE_FAIL:
				loading_staus_rl.setVisibility(View.VISIBLE);
				loading_dialog_content_layout.setVisibility(View.GONE);
				break;
			case OBTAIN_SHOP_SUCCESS:
				if (resultList != null) {
					shopList.addAll(resultList);
					Set<ViewSuppSearchExt> poiSet = new HashSet<ViewSuppSearchExt>();
					poiSet.addAll(shopList);
					shopList.clear();
					shopList.addAll(poiSet);
					Collections.sort(shopList);
				}
				shopAdapter.setIsSameCity(isSameCity);
				shopAdapter.setDataChange(shopList);
				loading_dialog_content_layout.setVisibility(View.GONE);
				if (isDropDown) {
					shopListView.onDropDownComplete("上次刷新时间:"
							+ DateUtil.getCurrentTime());
				}
				shopListView.setVisibility(View.VISIBLE);
				shopListView.onBottomComplete();
				loading_dialog_content_layout.setVisibility(View.GONE);
				break;
			case OBTAIN_SHOP_END:
				if (isDropDown) {
					shopListView.onDropDownComplete("上次刷新时间:"
							+ DateUtil.getCurrentTime());
				}
				isLastPage = true;
				if (resultList != null) {
					shopList.addAll(resultList);
					Set<ViewSuppSearchExt> poiSet = new HashSet<ViewSuppSearchExt>();
					poiSet.addAll(shopList);
					shopList.clear();
					shopList.addAll(poiSet);
					Collections.sort(shopList);
				}
				shopListView.setHasMore(false);
				shopListView.setVisibility(View.VISIBLE);
				loading_dialog_content_layout.setVisibility(View.GONE);
				shopListView.onBottomComplete();
				break;
			case OBTAIN_POI_START:
				isLoadPOI = true;
				if (poiSearch == null) {
					doSearchQuery();
				} else {
					nextSearch();
				}
				break;
			case OBTAIN_POI_END:// 结束
				// if (poiList.size() > 0) {
				// LogUtil.d("wxf", "POI is success.....");
				// shopList.addAll(poiList);
				// Set<ViewSuppSearchExt> poiSet = new
				// HashSet<ViewSuppSearchExt>();
				// poiSet.addAll(shopList);
				// shopList.clear();
				// shopList.addAll(poiSet);
				// Collections.sort(shopList);
				// } else {
				// if (shopList.size() == 0) {
				// handler.sendEmptyMessage(OBTAIN_POI_FAIL);
				// }
				// LogUtil.d("wxf", "POI is Empty.....");
				//
				// }
				if (shopList.size() == 0) {
					shopListView.setVisibility(View.GONE);
					loading_dialog_content_layout.setVisibility(View.GONE);
					loading_staus_rl.setVisibility(View.VISIBLE);
				} else {
					shopListView.setVisibility(View.VISIBLE);
					loading_dialog_content_layout.setVisibility(View.GONE);
					loading_staus_rl.setVisibility(View.GONE);

				}
				shopAdapter.setIsSameCity(isSameCity);
				shopAdapter.setDataChange(shopList);
				shopListView.setHasMore(false);
				shopListView.onBottomComplete();
				isLoadPOI = false;
				break;
			case OBTAIN_POI_FAIL:// 失败
				isLoadPOI = false;
				shopListView.setVisibility(View.GONE);
				progress_layout.setVisibility(View.VISIBLE);
				loading_staus_rl.setVisibility(View.VISIBLE);
				status_tv.setVisibility(View.GONE);
				break;
			case OBTAIN_POI_SUCCESS:// 获取成功
				if (poiList.size() > 0) {
					shopList.addAll(poiList);
					Set<ViewSuppSearchExt> poiSet = new HashSet<ViewSuppSearchExt>();
					poiSet.addAll(shopList);
					shopList.clear();
					shopList.addAll(poiSet);
					Collections.sort(shopList);
				} else {
					handler.sendEmptyMessage(OBTAIN_POI_FAIL);
				}
				if (isDropDown) {
					shopListView.onDropDownComplete("上次刷新时间:"
							+ DateUtil.getCurrentTime());
				}
				shopAdapter.setIsSameCity(isSameCity);
				shopAdapter.setDataChange(shopList);
				shopListView.setVisibility(View.VISIBLE);
				loading_dialog_content_layout.setVisibility(View.GONE);
				shopListView.onBottomComplete();
				break;
			case OBTAIN_POI_REFRESH:
				shopAdapter.notifyDataSetChanged();
				break;
			}
		};

	};

	public void nextSearch() {
		if (query != null && poiSearch != null && poiResult != null) {
			if (poiResult.getPageCount() - 1 > currentPage) {
				currentPage++;
				query.setPageNum(currentPage);// 设置查后一页
				poiSearch.searchPOIAsyn();
			} else {
				handler.sendEmptyMessage(OBTAIN_POI_END);
				LogUtil.d("wxf", "last page。。。");
			}
		}
	}

	@Override
	public void onPoiItemDetailSearched(PoiItemDetail detail, int rCode) {

		if (rCode == 0) {
			if (detail != null) {

				Dining dining = detail.getDining();

				for (ViewSuppSearchExt searchExt : poiList) {

					if (searchExt.getPoid().equals(detail.getPoiId())) {
						searchExt.setPoid(detail.getPoiId());
						searchExt.setTypeId(typeId);
						if (dining != null) {
							String type = dining.getTag();
							List<Photo> photos = dining.getPhotos();
							List<UrlImage> images = new ArrayList<UrlImage>();
							if (photos != null && photos.size() > 0) {
								for (Photo photo : photos) {
									UrlImage urlImage = new UrlImage();
									urlImage.setDes(photo.getTitle());
									urlImage.setUrl(photo.getUrl());
									images.add(urlImage);
								}
							}
							if (dining.getIntro() != null
									&& dining.getIntro().trim().length() != 0) {
								searchExt.setSupInfo(dining.getIntro());
							}
							searchExt.setPhotos(images);
							searchExt.setTag(type);
							searchExt.setRating(dining.getRating());
							searchExt.setServiceRating(dining
									.getServiceRating());
							searchExt.setTasteRating(dining.getTasteRating());
							searchExt.setEnvirRating(dining
									.getEnvironmentRating());
							if (dining.getCost() != null) {
								try {
									searchExt.setConsumptionPer(Double
											.parseDouble(dining.getCost()));
								} catch (Exception e) {

								}
							}

						}
					}
				}

			}
			Message msg = handler.obtainMessage();
			msg.what = OBTAIN_POI_REFRESH;
			handler.sendMessage(msg);
		}

	}

	@Override
	public void onPoiSearched(PoiResult result, int rCode) {

		if (rCode == 0) {
			if (result != null && result.getQuery() != null) {// 搜索poi的结果
				if (result.getQuery().equals(query)) {// 是否是同一条
					poiItems = result.getPois();
					poiResult = result;
					GsooApplication.poiResult = result;
					if (poiItems != null && poiItems.size() > 0) {
						doSearchPoiDetail(poiItems);
					} else {
						handler.sendEmptyMessage(OBTAIN_POI_END);
					}
				}
			} else {
				handler.sendEmptyMessage(OBTAIN_POI_END);
			}
		} else {
			LogUtil.e("onPoiSearched error Code = ", rCode + "");
			Message msg = handler.obtainMessage();
			msg.what = OBTAIN_POI_FAIL;
			handler.sendMessage(msg);
		}
	}

	public void doSearchPoiDetail(List<PoiItem> poiItems) {
		if (poiSearch != null) {
			poiList.clear();
			for (PoiItem poiItem : poiItems) {
				ViewSuppSearchExt searchExt = new ViewSuppSearchExt();
				String shopName = poiItem.toString();
				String des = poiItem.getTitle();
				double lat = poiItem.getLatLonPoint().getLatitude();
				double lng = poiItem.getLatLonPoint().getLongitude();
				String address = poiItem.getSnippet();
				String phone = poiItem.getTel();
				int distance = poiItem.getDistance();
				searchExt.setDistance(Double.parseDouble(distance + ""));
				searchExt.setLat(lat + "");
				searchExt.setLon(lng + "");
				searchExt.setTelPhone(phone);
				searchExt.setAddr(address);
				searchExt.setSuppName(shopName);
				searchExt.setSupInfo(des);
				searchExt.setDataType(ViewSuppSearchExt.TYPES[1]);
				searchExt.setPoid(poiItem.getPoiId());
				poiSearch.searchPOIDetailAsyn(poiItem.getPoiId());
				poiList.add(searchExt);
			}

			handler.sendEmptyMessage(OBTAIN_POI_SUCCESS);
		}
	}

	protected void doSearchQuery() {
		query = new PoiSearch.Query("", typeName, cityName);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
		query.setPageSize(7);// 设置每页最多返回多少条poiitem
		query.setPageNum(currentPage);// 设置查第一页
		query.setLimitDiscount(false);
		query.setLimitGroupbuy(false);
		poiSearch = new PoiSearch(this, query);
		poiSearch.setOnPoiSearchListener(this);
		if (GsooApplication.isSameCity) {
			LatLonPoint lp = new LatLonPoint(GsooApplication.lat,
					GsooApplication.lng);
			poiSearch.setBound(new SearchBound(lp, distanceQuery, true));
		}
		poiList = new ArrayList<ViewSuppSearchExt>();
		poiSearch.searchPOIAsyn();// 异步搜索

	}

	long waitTime = 2000;
	long touchTime = 0;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& KeyEvent.KEYCODE_BACK == keyCode) {
			long currentTime = System.currentTimeMillis();
			if ((currentTime - touchTime) >= waitTime) {
				Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
				touchTime = currentTime;
			} else {
				finish();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
